package com.xdy.server.core2;

import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author: XDY.
 * @Email: 2280944114@qq.com
 * @CreateTime: 2023-03-13  15:22
 * @Description: 解析web的xml配置文件
 * @Version: 1.0
 */
public class WebApp {

    private static WebContext webContext;
    private static List<ServletEntity> servletEntities;
    private static List<MappingEntity> mappingEntities;

    public static void init() throws ParserConfigurationException, IOException, SAXException {
        init("web.xml");
    }

    public static void init(String filename) throws ParserConfigurationException, SAXException, IOException {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        InputStream resource = WebApp.class.getClassLoader().getResourceAsStream(filename);
        WebHandler webHandler = new WebHandler();
        parser.parse(resource, webHandler);
        servletEntities = webHandler.getServletEntities();
        mappingEntities = webHandler.getMappingEntities();
        webContext = new WebContext(servletEntities, mappingEntities);
    }

    public static List<MappingEntity> getMappingEntities() {
        return Optional.of(mappingEntities).orElse(new ArrayList<>());
    }

    public static List<ServletEntity> getServletEntities() {
        return Optional.of(servletEntities).orElse(new ArrayList<>());
    }

    public static WebContext getWebContext() {
        return webContext;
    }

    /**
     * 根据uri返回对应的servlet
     *
     * @param uri
     * @return
     */
    public static Servlet getServletFromUrl(String uri) {
        String clazz = webContext.getClazz(uri);
        try {
            Class<?> aClass = Class.forName(clazz);
            //通过反射创建对应的servlet实例
            Servlet servlet = (Servlet) aClass.getConstructor().newInstance();
            //返回实例
            return servlet;
        } catch (Exception e) {
            return null;
        }
    }
}
